<?php

class Db {
	
	/* @var $db Db */
	private static $db;
	
	private static $debug = false;
	
	/* @var $pdo PDO */
	private $pdo;
	
	private function __construct() {
		try {
			$config = new PDOConfig();
			$this->pdo = new PDO($config->getDns(),
					$config->getUsername(),
					$config->getPassword(),
					array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
		}
		catch (PDOException $ex) {
			die("Unable to connect to database");	
		}
		
		
	}
	
	public static function getInstance() {
		if (!isset(self::$db))
			self::$db = new Db();
		return self::$db;
	}
	
	public function performQuery($query, $params = array()) {
		if (Db::$debug)
			var_dump($query);
		if (Db::$debug)
			var_dump($params);
		$sth = $this->pdo->prepare($query);
		$result = $sth->execute($params);
				
		if ($result)
			return $sth;
		return false;
	}
	
	public function getObjects($object, $where = '', $params) {
		
		try {
			if (class_exists($object))
				$obj = @new $object();
			else 
				throw new Exception("'".$object."' is a undefined Class");
		}
		catch (Exception $e) {
			echo $e->getMessage(); 
			die();
		}
		
		$objects = array();
		
		if (isset($obj)) {
			
			if (is_string($where) && $where != '')
				$where = ' WHERE '. $where;
			else {
				$where = '';
			}
			
			$objs =  db::getInstance()->performQuery('SELECT `id` FROM '. $object . $where, $params);
			
			foreach ($objs->fetchAll(PDO::FETCH_OBJ) as $obj) {
				$objects[$obj->id] = new $object($obj->id);
			}
		}
		return $objects;
		
	}
	
	public function getObject($object, $where = '', $params) {
		$objs = $this->getObjects($object, $where, $params);
		return array_shift($objs);
	}
	
	private function getLastId() {
		return $this->pdo->lastInsertId();
	}
	
	
	public static function setDebug($bool) {
		Db::$debug = $bool;
	}
	
}